<template>
  <div>
    <div class="vpc-network-network-search">
      <el-button
          class="search-wrapper-button"
          type="primary"
          @click="visible = true"
      >新 建</el-button>
    </div>
    <div class="vpc-network-table content-wrapper el-card el-card__body is-always-shadow">
      <TableComponent
          ref="tableRef"
          :table-list="state.tableData"
          :table-column-info="DHCPConfigByVpc"
          @updateData="setPageInfo"
          :options-button="optionsButton"
          :options-width="140"
          @defaultPageData="setDefaultPage"
      >
      </TableComponent>
    </div>

    <el-dialog v-model="visible" title="新建" class="add-vpc-DHCP-dialog">
      <el-form
          ref="netFormRef"
          :rules="rules"
          label-position="right"
          :model="addForm"
          class="sandbox-network-DHCP-form"
      >
        <el-form-item label="端口" prop="in_eth">
          <el-select
              filterable
              v-model="addForm.vpcPortID"
              class="w-full"
              clearable
          >
            <el-option
                v-for="item in portList"
                :label="item.name"
                :value="item.ID"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
            label="地址池开始地址"
            prop="ipStart"
        >
          <el-input
              v-model="addForm.ipStart"
          ></el-input>
        </el-form-item>
        <el-form-item
            label="地址池结束地址"
            prop="ipEnd"
        >
          <el-input
              v-model="addForm.ipEnd"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="visible = false">取 消</el-button>
          <el-button type="primary" @click="addDHCPConfigData"> 新 建 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import {
  onMounted,
  onUnmounted, reactive,
  ref,
  shallowReactive, watch,
} from 'vue';
import TableComponent from '@/components/table/TableComponent.vue';
import debounce from "lodash/debounce";
import { useRouter } from "vue-router";
import {DHCPConfigByVpc} from "@/views/simulation/defaultConfig";
import {
  addDHCPByVPCApi,
  delDHCPByVPCApi,
  getDHCPByVPCApi, getPortByVPCApi
} from "@/api/simulationApi/vpc";
import {ElMessage, ElMessageBox} from "element-plus";
import {IP_REGEXP} from "@/utils/common";
import {emitter} from "@/utils/bus";

// vpcID
const vpcID = ref('');

// 节点数据
const props = defineProps({
  vpcNode: null,
});

const router = useRouter();
const tableRef = ref(null);
const pageInfo = ref(null);
const keyword = ref('');
const state = shallowReactive({
  tableData: [],
});

// 表单
const visible = ref(false);
const netFormRef = ref();
const addForm = reactive({
  ipStart: '',
  ipEnd: '',
  vpcPortID: ''
});

const rules = {
  ipStart: [
    { required: true, message: '地址池开始地址不能为空', trigger: ['change', 'blur'] },
    {
      pattern: IP_REGEXP,
      message: '请输入合法IP',
      trigger: ['blur'],
    },
  ],
  ipEnd: [
    { required: true, message: '地址池结束地址不能为空', trigger: ['change', 'blur'] },
    {
      pattern: IP_REGEXP,
      message: '请输入合法IP',
      trigger: ['blur'],
    },
  ],
};

// 接口列表
const portList = ref([]);

const taskFunc = data => {
  const { msg } = data;
  const info = msg.update || msg.create;

  if(info.name.indexOf('Vpc') !== -1) {
    if((info.status === 2 || info.status === 3)) {
      getDHCPConfigByVpcData();
    }
  }
};
// 监听websocket消息通知
emitter.on('Task', taskFunc);

/**
 * 获取DHCP-VPC网络（防抖）
 * @type {DebouncedFuncLeading<(function(): Promise<void>)|*> | DebouncedFunc<(function(): Promise<void>)|*>}
 */
const getDHCPConfigByVpcData = debounce(async() =>{
  return getDHCPByVPCApi(vpcID.value, {
    keyword: keyword.value,
  }).then(res => {
    if (!(res instanceof Error)) {
      tableRef.value?.setPageInfo({ total: res.data.length, page: 1, pageSize: 9999 });
      state.tableData = res.data;
    }
  });
}, import.meta.env.VITE_INPUT_DEBOUNCE_TIME);

// 初始化页数
const setDefaultPage = arg => (pageInfo.value = arg);

const setPageInfo = arg => {
  pageInfo.value = arg;
  getDHCPConfigByVpcData();
};

const optionsButton = [
  {
    link: true,
    type: 'danger',
    name: '删除',
    click: item => {
      ElMessageBox.confirm(
          `删除路由配置 【${item.ip}】 ，删除后将不可恢复！`,
          '删除路由配置',
          {
            confirmButtonText: '删 除',
            cancelButtonText: '取 消',
            type: 'warning',
            center: true,
            customClass: 'delMessageBox',
            confirmButtonClass: 'delButtonClass',
          },
      ).then(async () => {
        delDHCPByVPCApi(vpcID.value, { vpcPortID: item.vpcPortID }).then(res => {
          if (!(res instanceof Error)) {
            ElMessage.success(`删除成功!`);
          }
        });
      });
    },
  }
];

/**
 * 确认添加DHCP
 */
const addDHCPConfigData = () => {
  netFormRef.value?.validate(async valid => {
    if (valid) {
      addDHCPByVPCApi(vpcID.value, addForm).then(res => {
        if (!(res instanceof Error)) {
          ElMessage.success('新建成功');
          visible.value = false;
          getDHCPConfigByVpcData();
        }
      });
    }
  });
};

/**
 * 获取接口列表
 */
const getPortList = (ports) =>{
  getPortByVPCApi(vpcID.value).then(res => {
    if (!(res instanceof Error)) {
      // 过滤未生成数据（已存在的数据也需要过滤）
      if(res.data?.length > 0) {
        portList.value = res.data.filter(item => item.generate && !item.dhcpServer );
      }
    }
  });
}

// 监听传递过来的节点数据
watch(() =>props.vpcNode, (val) =>{
  vpcID.value = props.vpcNode.ID;

  if (vpcID.value) {
    getDHCPConfigByVpcData();
  }
},  { immediate: true } )

watch(
    visible,
    () => {
      if (!visible.value) {
        netFormRef.value?.resetFields();
        addForm.vpcPortID = '';
      } else {
        getPortList();
      }
    },
    { immediate: false },
);

/**
 * 挂载-生命周期
 */
onMounted(() =>{

});

/**
 * 卸载-生命周期（主要处理清除定时器、解绑操作）
 */
onUnmounted(() => {
  emitter.off('Task', taskFunc);
});
</script>
<style lang="scss" scoped>
.vpc-network-network-search {
  margin-top: 12px;
  position: relative;

  button {
    margin-left: 16px;
  }

  .vm-manage-search {
    top: -10px!important;
  }
}

.vpc-network-table {
  padding-top: 12px;
  height: calc(100vh - 366px)!important;
}

:deep(.paginationclass) {
  display: none;
}

:deep(.add-vpc-DHCP-dialog) {
  width: 560px;
  .el-form {
    max-width: 480px;
    .el-form-item__label {
      width: 160px;
    }
  }
}
</style>
